<template>
    <div class="custom-tree-container">
        <p>菜单管理</p>
        <!-- <button @click="getSelected">获取</button>
        <button @click="setCheckedKeys">设置选中</button> -->
        <el-tree ref="treeRef" style="max-width: 600px" :data="dataSource" show-checkbox node-key="id"
            default-expand-all :expand-on-click-node="false" :props="defaultProps">
            <template #default="{ node, data }">
                <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <span v-if="singlePage">
                        <a style="margin-left: 8px" @click="append(data)"> 新增子菜单 </a>
                        <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                            icon-color="#626AEF" title="确定完成此任务么？" @confirm="handleDeleteConfirmEvent(node, data)">
                            <template #reference>
                                <a style="margin-left: 8px"> 删除当前菜单 </a>
                                <!-- <el-button type="primary" :icon="Delete" /> -->
                            </template>
                        </el-popconfirm>
                    </span>
                </span>
            </template>
        </el-tree>
        <el-form style="margin-top: 10px;" v-if="!singlePage">
            <el-button type="primary" icon="el-icon-search" size="default" @click="menuSettingSubmit">菜单配置保存</el-button>
        </el-form>
    </div>

    <!-- 添加或修改参数配置对话框 start-->
    <el-dialog :title="title" width="500px" append-to-body draggable v-model="outerVisible">
        <el-row :gutter="15">
            <el-form :model="addFormData" :rules="rules" :size="formSize" label-width="150px" ref="addFormRef"
                style="max-width: 600px">
                <el-col :span="24">
                    <el-form-item label="中文名称" prop="name">
                        <el-input v-model="addFormData.name" placeholder="请输入菜单中文名称" clearable
                            :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="英文名称" prop="enName">
                        <el-input v-model="addFormData.enName" placeholder="请输入菜单英文名称" clearable
                            :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item size="large">
                        <el-button type="primary" @click="submitAddForm(addFormRef)">保存</el-button>
                        <el-button @click="outerVisible = false">取消</el-button>
                        <el-button @click="resetForm(addFormRef)">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-form>
        </el-row>
        <!-- 也可以用这种方式，看起来按钮更好看些，但是默认不居中，需要调下。 -->
        <!-- <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div> -->
    </el-dialog>
    <!-- 添加或修改参数配置对话框 end -->
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive, toRefs, watch } from 'vue'
import { showErrorMsg, showSuccessMsg, resetForm } from '@/api/common'
import { ElTree } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import type { FormInstance, FormRules, ComponentSize } from 'element-plus'
import { listAllMenus, addMenu, deleteMenu } from "@/api/menu/menu";
import { roleMenuSetting } from "@/api/role/role";
import { InfoFilled } from '@element-plus/icons-vue'
import type { ApiResponse, OnlyIdRequest } from '@/api/common';
import type { Tree, DefaultProps, MenuAddRequest, RoleMenuRequest } from '@/api/menu/menu'
let roleMenuRequest = reactive<RoleMenuRequest>({
    roleId: 1,
    menuIdList: [],
})
const treeRef = ref<InstanceType<typeof ElTree>>()
const setCheckedKeys = () => {
    treeRef.value!.setCheckedKeys(props.selectedIdList, false)
}
const props = withDefaults(defineProps<{
    // 是否是从左侧菜单进入
    singlePage: boolean,
    roleId: number,
    selectedIdList: number[],
}>(), {
    singlePage: true,
    selectedIdList: () => [],
})
let onlyIdRequest = reactive<OnlyIdRequest>({
    id: 1,
})
let title = ref('新增菜单')
let outerVisible = ref(false)
const formSize = ref<ComponentSize>('large')
const addFormRef = ref<FormInstance>()
let addFormData = reactive<MenuAddRequest>({
    name: '',
    enName: '',
    parentId: 0,
})
let rules = reactive<FormRules<MenuAddRequest>>({
    name: [{
        required: true,
        message: '请输入菜单中文名称',
        trigger: 'change'
    }],
    enName: [{
        required: true,
        message: '请输入菜单英文名称',
        trigger: 'change'
    }],
})
const submitAddForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            addFormData.parentId = currentTreeId
            addMenu(addFormData).then((res: ApiResponse<string>) => {
                if (res.status != 200) {
                    showErrorMsg(res.msg);
                } else {
                    showSuccessMsg("新增成功");
                    outerVisible.value = false;
                    handleListAllMenus();
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const defaultProps = ref<DefaultProps>({
    children: 'children',
    label: 'name'
})
let currentTreeId = 0;
const append = (data: Tree) => {
    currentTreeId = data.id;
    outerVisible.value = true;
    // const newChild = { id: id++, label: 'testtest', name: 'testtest', enName: '', children: [] }
    // if (!data.children) {
    //     data.children = []
    // }
    // data.children.push(newChild)
    // dataSource.value = [...dataSource.value]
}
const handleDeleteConfirmEvent = (node: Node, data: Tree) => {
    onlyIdRequest.id = data.id;
    deleteMenu(onlyIdRequest).then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            showSuccessMsg("删除成功")
            handleListAllMenus();
        }
    });

    // const parent = node.parent
    // const children: Tree[] = parent.data.children || parent.data
    // const index = children.findIndex((d) => d.id === data.id)
    // children.splice(index, 1)
    // dataSource.value = [...dataSource.value]
}
const dataSource = ref<Tree[]>([]);
// mock data
const dataSource1 = ref<Tree[]>([
    {
        id: 1,
        name: 'Level one 1', enName: '',
        children: [
            {
                id: 4,
                name: 'Level two 1-1', enName: '',
                children: [
                    {
                        id: 9,
                        name: 'Level three 1-1-1', enName: '',
                    },
                    {
                        id: 10,
                        name: 'Level three 1-1-2', enName: '',
                    },
                ],
            },
        ],
    },
    {
        id: 2,
        name: 'Level one 2', enName: '',
        children: [
            {
                id: 5,
                name: 'Level two 2-1', enName: '',
            },
            {
                id: 6,
                name: 'Level two 2-2', enName: '',
            },
        ],
    },
    {
        id: 3,
        name: 'Level one 3', enName: '',
        children: [
            {
                id: 7,
                name: 'Level two 3-1', enName: '',
            },
            {
                id: 8,
                name: 'Level two 3-2', enName: '',
            },
        ],
    },
])
onMounted(() => {
    handleListAllMenus();
})
// 监听 selectedIdList 的变化
watch(() => props.selectedIdList, (newVal) => {
    // 设置被选中的菜单
    setCheckedKeys();
});
const handleListAllMenus = () => {
    listAllMenus().then((res: ApiResponse<Tree[]>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            dataSource.value = res.data;
        }
    });
}
const menuSettingSubmit = () => {
    let selectIdList = treeRef.value!.getCheckedKeys(true) as number[];
    roleMenuRequest.roleId = props.roleId;
    roleMenuRequest.menuIdList = selectIdList;
    roleMenuSetting(roleMenuRequest).then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            showSuccessMsg("配置成功");
        }
    })
}
</script>
<style>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>